﻿using System;
using System.Text.RegularExpressions;
using Nexia.FluentHtmlElements.Encoders;
using Nexia.FluentHtmlElements.IoC;

namespace Nexia.FluentHtmlElements.Utilities
{
	/// <summary>
	/// A component which strips HTML from strings.
	/// </summary>
	public class HtmlStripper : IHtmlStripper
	{
		private static readonly Regex HtmlRegex = new Regex("<[^>]*>", RegexOptions.Compiled);

		/// <summary>
		/// Initializes a new instance of the <see cref="HtmlStripper" /> class.
		/// </summary>
		public HtmlStripper() : this(DependencyFactory.GetNamedInstance<IEncoder>("html"))
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="HtmlStripper" /> class using the given <see cref="IEncoder" /> for Html Entiziation.
		/// </summary>
		/// <remarks>This method is mostly used for unit testing.</remarks>
		/// <param name="htmlEncoder"></param>
		public HtmlStripper(IEncoder htmlEncoder)
		{
			HtmlEncoder = htmlEncoder;
		}

		/// <summary>
		/// The IEncoder to use to entitize html.
		/// </summary>
		private readonly IEncoder HtmlEncoder;

		/// <summary>
		/// Convert the given string to plain text.
		/// </summary>
		/// <remarks>It is assumed that the given html is valid html and that it does not contain style or script tags.</remarks>
		/// <param name="html">The html input string</param>
		/// <returns>A string containing no HTML</returns>
		public string ConvertToPlainText(string html)
		{
			if (string.IsNullOrEmpty(html))
				return string.Empty;

			var markupStripped = HtmlRegex.Replace(html, String.Empty);

			return HtmlEncoder.Decode(markupStripped);
		}
	}
}
